﻿using Castle.DynamicProxy;

namespace Vasuleg.UIDrive
{
    public static class EntityParsing
    {
        public static T CreateEntity<T>() where T : class, new()
        {
            return CreateEntityWithTarget(new T());
        }

        public static T CreateEntityWithTarget<T>(T target) where T : class
        {
            return ProxyGeneratorUtils.CreateClassProxyWithTarget(target, new EntityInterceptorImpl(target));
        }

        public static EntityInterceptorImpl GetEntityInterceptor<T>(T instance) where T : class
        {
            if (instance is not IProxyTargetAccessor proxyTargetAccessor)
            {
                return null;
            }

            var interceptors = proxyTargetAccessor.GetInterceptors();
            foreach (var interceptor in interceptors)
            {
                if (interceptor is EntityInterceptorImpl impl)
                {
                    return impl;
                }
            }

            return null;
        }
    }
}